<template>
  <div class="search-container">
    <form style="position:fixed;top:0;z-index:99;width:100%" action="/">
      <van-search
        background="rgb(50, 150, 250)"
        v-model.trim="value"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
       
        @cancel="onCancel"
      />
    </form>

    <!-- 搜索结果 -->
    <search-result :value='value' v-if="searchFlag"></search-result>
    <!-- 搜索结果 -->

    <!-- 搜索建议 -->
    <search-suggest @search="onSearch" :value='value'  v-else-if="value"></search-suggest>
    <!-- 搜索建议 -->

    <!-- 搜索历史 -->
    <search-history
      @delhistory="delhistory"
      @delcell="delcell"
      :historyData="historyData"
      v-else
    ></search-history>
    <!-- 搜索历史 -->
  </div>
</template>

<script>
import searchHistory from "./components/search-history";
import searchSuggest from "./components/search-suggest";
import searchResult from "./components/search-result";
import { Toast } from "vant";


//  _   {deepclone:function(){}}

import { setItem, getItem, removeItem } from "@/utlis/storage";

export default {
  data() {
    return {
      value: "",
      searchFlag: false, //  显示搜索结果组件
      historyData: getItem("historyDataArr") || [] ,//  初次进入  就获取本地缓存  本地缓存有数据就使用 没有就去空数组
     
   };
  },
 
  methods: {
    onSearch(val) {
      this.value=val
      
      this.searchFlag = true;

      //  [1,2,3,4,5]   4 =====【4，1，2，3，5】  findIndex()====index     splice(index,1)

      //  数据持久化

      this.historyData.unshift(this.value);
      setItem("historyDataArr", this.historyData);
    },
    onCancel() {
      this.$router.back();
    },
    

    

    //   清除本地缓存
    delhistory() {
      removeItem("historyDataArr");
      this.historyData = [];
    },
    // 删除单个
    delcell(index, delFlag) {
      /* 
    如果 delFlag  ==true   就删除
    如果 delFlag==false   就显示搜索结果
    */
      //console.log(index,8888);
      if (delFlag) {
        this.historyData.splice(index, 1);
        setItem("historyDataArr", this.historyData);
      } else {
        this.searchFlag = true;//  显示搜索结果
      }
    }
  },

  components: {
    searchHistory,
    searchSuggest,
    searchResult
  }
};
</script>
<style scoped lang='less'>
.search-container{
  padding-top: 120px;
}

</style>
